<?php
/**
 * Created by JetBrains PhpStorm.
 * User: xiaobai
 * Date: 13-5-24
 * Time: 上午10:18
 * To change this template use File | Settings | File Templates.
 */
class Keyword_crawl_model extends CI_Model {

    private $_platform;
    private $_page;
    private $_word;
    private $_write_db;

    function __construct()
    {
        parent::__construct();
        $this->load->driver('cache', array('adapter' => 'redis'));
        $this->load->library('encrypt');
        $this->load->database();
        $this->_write_db = $this->load->database('master', TRUE);
        $this->_platform = $this->input->post('platform');
        $this->_word = $this->input->post('word');
        if($this->input->post('page') == FALSE) {
            $this->_page = 1;
        } else if($this->input->post('page') > $this->config->item('max_page')) {
        	//如果传入nopage_limit参数..则不受页数限定
        	$this->_page = ($this->input->post('nopage_limit')) ? $this->input->post('page') : $this->config->item('max_page');
        } else {
            $this->_page = $this->input->post('page');
        }
    }

    public function find_in_cache() {
        $cache_key = md5($this->_platform . $this->_page . $this->_word);
        return $this->cache->get($cache_key);
    }

    public function save_crawl_result($result_string) {
        $cache_key = md5($this->_platform . $this->_page . $this->_word);
        $result_array = array(
            'platform' => $this->_platform,
            'page'     => $this->_page,
            'word'     => $this->_word,
            'result'   => $result_string
        );
        return $this->cache->save($cache_key, json_encode($result_array),  $this->config->item('keyword_result_life'));
    }

    public function find_in_db() {
        $cache_key = md5($this->_platform . $this->_page . $this->_word);
        $this->db->select('content');
        $this->db->from('crawl_history');
        $this->db->where('key', $cache_key);
        $this->db->where('ctime > '.(time() - $this->config->item('keyword_result_life')));
        $this->db->limit(1);
        $query = $this->db->get();

        if($query->num_rows() <= 0) {
            $this->_write_db->where('ctime <', (time() - $this->config->item('keyword_result_life')));
            $this->_write_db->delete('crawl_history');
            return NULL;
        } else {
            return $query->row_array();
        }
    }

    public function save_in_db($result_string) {
        $cache_key = md5($this->_platform . $this->_page . $this->_word);
        $data = array(
            'key' => $cache_key,
            'ctime' => time(),
            'platform' => $this->_platform,
            'word'  => mysql_real_escape_string($this->_word),
            'page'  => $this->_page,
            'content' => $result_string
        );

        $this->_write_db->insert('crawl_history', $data);
    }
}
